package club.janna.rpcdemo.client.discover;

import club.janna.rpcdemo.domain.ServiceInfo;
import org.I0Itec.zkclient.ZkClient;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ZooKeeperServiceDiscover extends AbstractServiceDiscover {

    private ZkClient zkClient;
    private String zookeeperAddress;
    private static final String PATH_PREFIX = "/RPCServices";

    public ZooKeeperServiceDiscover(String zookeeperAddress) {
        this.zookeeperAddress = zookeeperAddress;
    }

    @PostConstruct
    public void init() {
        zkClient = new ZkClient(zookeeperAddress);
        List<String> services = zkClient.getChildren(PATH_PREFIX);
        for (String serviceName : services) {
            List<String> nodes = zkClient.getChildren(PATH_PREFIX + "/" + serviceName);
            List<ServiceInfo> infoList = new ArrayList<>(nodes.size());
            for (String node : nodes) {
                String[] arr = node.split(":");
                infoList.add(ServiceInfo.builder()
                        .ip(arr[0])
                        .port(Integer.parseInt(arr[1]))
                        .protocol(ServiceInfo.Protocol.valueOf(arr[2]))
                        .build());
            }
            serviceMap.put(serviceName, infoList);
        }
    }
}
